package baohuajie.com.service.utils;

/**
 * @author goujian
 * @description: TODO
 * @date 2022/3/2 7:16 下午
 */


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;

import java.net.InetAddress;

/**
 * @author jijiecong
 * @version 1.0
 * @date 2021/12/1 14:21
 * @description 雪花算法生成id工具类
 */
@Slf4j
public class SnowFlakeUtil {

    private static final String WORK_ID_KEY = "worker.id";

    private static SnowflakeShardingKeyGenerator keyGenerator;

    /**
     * 单例
     */
    public static SnowflakeShardingKeyGenerator getInstance() {

        if (keyGenerator == null) {

            synchronized (SnowFlakeUtil.class) {

                // 双重校验
                if (keyGenerator == null) {

                    keyGenerator = new SnowflakeShardingKeyGenerator();

                    // 设置workId，注意一定要转换成String再put进去
                    keyGenerator.getProperties().put(WORK_ID_KEY, getWorkId());
                }

            }

        }

        return keyGenerator;
    }

    /**
     * 获取id
     *
     * @return id
     */
    public static Long getId() {

        Long id = (Long) getInstance().generateKey();

        log.info("___此次生成的id为：{}", id);

        return id;

    }

    /**
     * 获取workId，保证分布式服务下每台机器都不同
     * 使用机器ip都最后3位作为workId
     *
     * @return workId
     */
    public static String getWorkId() {
        String workId = "0";

        try {

            InetAddress inetAddress = InetAddress.getLocalHost();

            String localIp = StringUtils.isBlank(inetAddress.getHostAddress()) ?
                    null : inetAddress.getHostAddress().trim();

            if (StringUtils.isNotBlank(localIp) && localIp.contains(".")) {

                String[] ipArray = localIp.split("\\.");

                workId = ipArray[ipArray.length - 1];

                log.info("___workId:{}", workId);

            }

        } catch (Exception e) {

            log.error("获取workId失败", e);

        }

        return workId;
    }

    public static void main(String[] args) {
        long id = SnowFlakeUtil.getId();
        System.out.println(id);
    }
}
